/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.model;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 *
 * @author Timon Veenstra
 */
@NamedQueries(value = {
    @NamedQuery(name = Field.Q_FIND_ALL_FIELDS, query = "select p from Field p"),
    @NamedQuery(name = Field.Q_FIND_ALL_VALID_FIELDS, query = "select f from Field f where :date between f.startDate and f.endDate or (f.endDate is null and f.startDate < :date)")
})
@Entity
@Table(name = "FIELD")
public class Field extends Surface implements Serializable, Persistable, Transferable {

    
    public static final String Q_FIND_ALL_FIELDS = "findAllFields";
    public static final String Q_FIND_ALL_VALID_FIELDS = "findAllValidFields";
    
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID")
    private long id;
    
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "FIELD_FILE_ID")
    private FieldFile fieldFile;
     
    @OneToMany(cascade=CascadeType.ALL, mappedBy="field")
    private Set<PartField> partField;
    

    public long getId() {
        return id;
    }
  
    public FieldFile getFieldFile() {
        return this.fieldFile;
    }

    public void setFieldFile(FieldFile fieldFile) {
        FieldFile old = this.fieldFile;
        this.fieldFile = fieldFile;
        getPropertyChangeSupport().firePropertyChange("fieldFile", old, fieldFile);
    }

    public Set<PartField> getPartFields() {
        return partField;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(this.getId());
        sb.append(" ");
        sb.append(this.getName()); 
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Field other = (Field) obj;
        if (this.id != other.id) {
            return false;
        }
        if ((getName() == null) ? (other.getName() != null) : !getName().equals(other.getName())) {
            return false;
        }
        if (this.fieldFile != other.fieldFile && (this.fieldFile == null || !this.fieldFile.equals(other.fieldFile))) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 29 * hash + (int) (this.id ^ (this.id >>> 32));
        hash = 29 * hash + (getName() != null ? getName().hashCode() : 0);
        hash = 29 * hash + (this.fieldFile != null ? this.fieldFile.hashCode() : 0);
        return hash;
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return new DataFlavor[]{DATA_FLAVOR};
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return DATA_FLAVOR.equals(flavor);
    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (flavor == DATA_FLAVOR) {
            return this;
        } else {
            throw new UnsupportedFlavorException(flavor);
        }
    }

    /**
     * Create a PartField from a Field and a selected ProductionUnit
     * 
     * The new PartField will inherit start- and enddate from ProductionUnit and Acreage and WKT from the Field
     */
    public static PartField createPartFieldFrom(Field field, ProductionUnit productionUnit){       
        PartField.Builder toReturn = new PartField.Builder().setAcreage(field.getAcreage()).setStartDate(field.getStartDate()).setEndDate(field.getEndDate()).setWKT(field.getWKT()).setField(field);
        
        if(productionUnit != null){
            toReturn.setProductionUnit(productionUnit);
        }
        
        return toReturn.build();
    }
        
    /**
     * Field builder class
     *
     * usage: Field field = new Field.Builder().setName("someName").build();
     *
     */
    public static class Builder extends Surface.Builder<Field> {

        public Builder() {
            super(new Field());
        }

        public Field.Builder setFieldFile(FieldFile fieldFile) {
            getSurface().setFieldFile(fieldFile);
            return this;
        }

        @Override
        public Field build() {
            return getSurface();
        }
    }
}
